const express = require("express");
const path = require("path");
const fs = require("fs");
const md5 = require("md5");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const cors = require('cors');

const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));

// 密码加密中间件
const passwdCrypt = (req, res, next) => {
    const passwd = req.body.password;
    req.body.passwdCrypted = md5(passwd + md5(passwd).substring(0, 16));
    next();
};

// 中间件：验证客户端发送过来的token
const checkToken = async function (req, res, next) {
    // 处理并获取token
    let tempArr = req.headers.authorization.split(" ");
    let token = tempArr[tempArr.length - 1];
    console.log(req.headers.authorization)
    if (!token) {
        // 没有token
        res.status(403).send({
            code: 403,
            info: "illegal access",
        });
    } else {
        // 尝试去验证token
        try {
            let { userId } = jwt.verify(req.headers.authorization, jwt_secret);
            // 查询当前用户是否可用
            let data = await Model.findOne({ userId });
            if (!data) {
                res.status(403).send({
                    code: 400,
                    info: "illegal access",
                });
            } else {
                req.body.userInfo = data;
                next();
            }
        } catch (error) {
            res.status(403).send({
                code: 400,
                info: "bad request",
            });
        }
    }
};

// 获取初始化密码，注意这里需要传递 post 参数 x-www-form-urlencoded password（用完即删）
// app.post("/init", passwdCrypt, (req, res) => {
//     res.send("加密后的密码为:" + req.body.passwdCrypted);
//     // 加密后的密码为:f5e441058f943860805d9a9af7318dc0【明文密码是123456】
// });

// 读取JWT的密钥
const jwt_secret = fs.readFileSync(path.join(__dirname, ".sec"), "utf-8");
// 引入 mongoose
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/maizuo", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
const UserSchema = new mongoose.Schema({
    userId: {
        type: Number,
        required: true,
    },
    mobile: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true,
    },
    headIcon: String,
    gender: Number,
});
const Model = mongoose.model("User", UserSchema, "users");

app.use(cors());

// 登录验证接口
app.post("/api/v1/login", passwdCrypt, async (req, res) => {
    console.log(req.body);
    let { mobile, passwdCrypted } = req.body;
    let result = await Model.findOne({ mobile, password: passwdCrypted });
    if (result) {
        res.send({
            code: "1000",
            msg: "ok",
            data: {
                _token: jwt.sign(
                    {
                        userId: result.userId,
                        mobile: result.mobile,
                    },
                    jwt_secret
                ),
            },
        });
    } else {
        res.send({
            code: "9999",
            info: "mobile or password is invalid",
        });
    }
});

app.get("/api/v1/user_info", checkToken, (req, res) => {
    let { userId, headIcon, gender, mobile } = req.body.userInfo;
    res.send({
        code: 200,
        msg: "ok",
        data: {
            userinfo: {
                userId,
                mobile: mobile.substr(0, 7) + "****",
                gender,
                headIcon,
            }
        }
    });
});

app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`服务器成功启动：http://127.0.0.1:${port}!`));